<!-- 
    Document   : index
    Created on : 27-aug-2008, 8:35:06
    Author     : jeroen
    Thanks to: Geert Vandamme, http://luke.breuer.com/tutorial/js_contextmenu.htm,
            http://elouai.com/javascript-drag-and-drop.php,
            http://javascript.internet.com/image-effects/image-rotate-with-canvas.html
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>Welcome to JSPicture, the program to organize and print your pictures</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    
    <style>
        root { 
            display: block;
        }

        canvas {
            border: 3px solid red;
        }
        
        .visible {
            display: block;
        }

        .hidden {
            display: none;
        }

        #right {
            position: fixed;
            right: 5px;
            display: none;
            border-style: groove;
            border-width: 0 0 4px 4px;
            border-color: blue;
        }
        
        #divContext {
            border: 1px solid blue;
            display: none;
            position: absolute;
        }
        
        #divResize {
            display: none;
            border: 1px dashed blue;
            background-color: silver;
        }
        
        #divRotate {
            display: none;
            border: 1px dashed blue;
            background-color: silver;
        }
        
        #right ul {
            list-style: none;
        }
        
        #right ul li a{
            float: left;
            color: black;
            font-weight: bold;
            padding: 0.5em;
            text-decoration: none;
        }

        #main {
            float: left;
        }
        
        .cmenu {
            margin: 0;
            padding: 0.3em;
            list-style-type: none;
            background-color: white;
        }
        
        .cmenu li:hover {}
        
        .cmenu hr {
            border: 0;
            border-bottom: 1px solid grey;
            margin: 3px 0px 3px 0px;
            width: 10em;
        }
        
        .cmenu a {
            border: 0 !important;
         }
        
        .cmenu a:hover {
            text-decoration: underline !important;
         }
        
        .cmenu .topSep {
            font-size: 90%;
            border-top: 1px solid gray;
            margin-top: 0.3em;
            padding-top: 0.3em;
        }
        
        .dragme {
            position:relative;
        }
    </style>
    
  </head>
  <body onload="InitContext()">
      <div id ="main">
        <p>Welcome to JSPicture.</p>
        <form>
            <input type="button" value="Get a list of your pics" onclick="openSelection()" />
        </form>
        
       </div>
    
    <div id="right" >
        
        
    </div>
    
    <div id="divContext" >
            <ul class="cmenu">
                <li><a id="resize" href="#" onclick="resize()">Resize the image</a></li>
                <li><a id="comment" href="#" onclick="addComment()">Add a comment</a></li>
                <li><a id="rotate" href="#" onclick="rotateInit()">Rotate</a></li>
                <li><a id="delete" href="#" onclick="removeImage()">Delete Image</a></li>
                <li><a id="cancel" onclick="CloseContext()">Cancel</a></li>
            </ul>
            
            <div id="divResize">
                <table>
                    <tr>
                        <td id="textWidth"></td> <td id="valueWidth"></td> <td id="buttonsWidth"></td>
                    </tr>
                    <tr>
                        <td>Keep w/h ratio?</td> <td><form><input id="checkboxResize" type="checkbox" onchange="controlWidthHeightRatio()" checked="true"/></form></td>
                    </tr>
                    <tr>
                        <td id="textHeight"></td> <td id="valueHeight"></td> <td id="buttonsHeight"></td>
                    </tr>
                    <tr>
                        <td><a href="#" onclick="originalSize()">Return to original size</a></td>
                    </tr>
                    <tr>
                        <td><a href="#" onclick="closeResize()">Close</a></td>
                    </tr>
                </table>
            </div>
            
            <div id="divRotate">
                <input type="button" value="0°" onclick="rotate(0);">
                <input type="button" value="90°" onclick="rotate(90);">
                <input type="button" value="180°" onclick="rotate(180);">
                <input type="button" value="-90°" onclick="rotate(-90);">
            </div>
    </div>
    
    <div id="paging" style="display: none;">
            <ul>
                <li id="previous" ><a href="#" onclick="setContent('-')">previous</a></li>
                <li id="next" ><a href="#" onclick="setContent('+')">next</a></li>
            </ul>
    </div>
  
  <script type="text/javascript" >
    var rootDir="";
    
    var widthRight = 200;
    var widthMain = window.screen.width - widthRight - 40;
    
    var target = "";

    var imageList =new Array();
    var index = 0;
    var numberImages = 3;

    var choice = "<form><p>What's the path of the directory of the images you wish to use? <input type='text' id='pathImages' value='/home/jeroen/My_Documents/Images' /></p><p><input type='button' value='See images' onclick='loadImages(\"pathImages\")'/></p></form>";

    var _replaceContext = false; // replace the system context menu?
    var _mouseOverContext = false; // is the mouse over the context menu?
    var _divContext = $('divContext'); // makes my life easier

    var ie=document.all;
    var nn6=document.getElementById&&!document.all;
    var isdrag=false;
    var x,y;
    var dobj;
    
    var widthHeightRatio=null;
    var stepResizingWidth = null;
    var stepResizingHeight = null;
    var originalWidth = null;
    var originalHeight = null;
    
    var imageResize = null;
    var scaleNumber = 0.00;
 
    function openSelection()
    {
        //removing the content of the array
        var arrLength = imageList.length;
        for(var i=0;i<arrLength;i++){
            imageList.shift();
        }
        
        $('right').style.display = "block";
        document.getElementById("right").innerHTML = choice;
        //newwindow=window.open('pathImages.html','pathImages','height=400,width=400,scrollbars=yes,resizable=yes,status=yes');return false;
    }

    function Place(imageURL)
    {
        var content = document.getElementById("main").innerHTML
        
        content += "<div id='"+imageURL+"' class='dragme'>";
        content += "<canvas >";
        content += "<img src='"+imageURL+"' style='display:none;' />";
        content += "<input type='hidden' id='dx'>0</input>";
        content += "<input type='hidden' id='dy'>0</input>";
        content += "<input type='hidden' id='angle'>0</input>";
        content += "<input type='hidden' id='canvasWidth'>0</input>";
        content += "<input type='hidden' id='canvasHeight'>0</input>";
        content += "</canvas>";
        content += "<p></p>";
        content += "<textarea cols='50' style='display:none;' rows='10' class='commentBox' onkeyup='submitComment(event)' onclick=getFocus(event)></textarea>";
        content += "</div>";
        
        document.getElementById("main").innerHTML = content;
        
        var img = $(imageURL).getElementsByTagName('img')[0];
        img.width = img.width < widthMain?img.width:widthMain;
        
        img.parentNode.getElementsByTagName("input")[3].value = img.width;
        img.parentNode.getElementsByTagName("input")[4].value = img.height;
        
        target = document.getElementById(imageURL).getElementsByTagName("canvas")[0];
        target.width = img.width;
        target.height = img.height;
        target.getContext("2d").drawImage(img,target.getElementsByTagName("input")[0].value,target.getElementsByTagName("input")[1].value,img.width,img.height);
        
        target = null;
        
        drawExistingImages();
    }
    
    function removeImage()
    {
        var nodeList = $('main').childNodes;
        var i = 0;
        for(i; i < nodeList.length; i++)
            {
                if(nodeList[i].id == target.src.split("file://")[1])
                {
                    $('main').removeChild(nodeList[i]);
                    break;
                }
            }
        CloseContext();
    }
        
    function addComment()
    {
        CloseContext();
        var textarea = target.parentNode.getElementsByTagName("textarea")[0];
        textarea.style.display='block';
        textarea.value = target.parentNode.getElementsByTagName("p")[0].innerHTML;
        
        target.parentNode.getElementsByTagName("textarea")[0].focus();
        //target.parentNode.getElementsByTagName("p")[0].innerHTML = "haha";
    }
    
    function submitComment(e) {
    var KeyID = e.keyCode;
    
    if(KeyID==13){
        target.parentNode.getElementsByTagName("textarea")[0].style.display='none';
        var message = target.parentNode.getElementsByTagName("textarea")[0].value;
        var par = target.parentNode.getElementsByTagName("p")[0];
        par.innerHTML=message;
        
        //reset value of textarea
        target.parentNode.getElementsByTagName("textarea")[0].value="";
        }
    }
    
    function getFocus(event)
    {
        event.target.focus();
    }

    function controlWidthHeightRatio()
    {
        if( $('checkboxResize').checked )
            widthHeightRatio = target.width/target.height;
    }
    
    function resize()
    {
        widthHeightRatio = target.width/target.height;

        $('divResize').style.display = "block";
        
        //imageResize = target.parentNode.getElementsByTagName("img")[0];
        imageResize = target;
        
        $('textWidth').innerHTML= "width: ";
        $('valueWidth').innerHTML= imageResize.width;
        $('buttonsWidth').innerHTML="";
        $('buttonsWidth').innerHTML += imageResize.width > 40 ?"<input type='button' value='-' onclick='resizer(\"rw\")' />":"";
        $('buttonsWidth').innerHTML += imageResize.width+ stepResizingWidth < widthMain ? " <input type='button' value='+' onclick='resizer(\"ew\")' />" : "";
        
        $('textHeight').innerHTML= "height: ";
        $('valueHeight').innerHTML= imageResize.height;
        $('buttonsHeight').innerHTML = "";
        $('buttonsHeight').innerHTML += imageResize.height > 40 ? "<input type='button' value='-' onclick='resizer(\"rh\")' />" : "" ;
        $('buttonsHeight').innerHTML += imageResize.height + stepResizingHeight < window.screen.height ? " <input type='button' value='+' onclick='resizer(\"eh\")' />  " : "";
    }
    
    function resizer(action)
    {
        if(action.split('w').length > 1)
            resizeWidth(action);
        else resizeHeight(action);
    }
    
    function resizeWidth(action)
    {
        if(action=='rw')
        {
            imageResize.width -= stepResizingWidth;
        }
        else
        {
            imageResize.width += stepResizingWidth
        }
        
        imageResize.height = $('checkboxResize').checked ? imageResize.width/widthHeightRatio : imageResize.height;
        
        $('valueWidth').innerHTML= imageResize.width;
        $('valueHeight').innerHTML= imageResize.height;
        $('buttonsWidth').innerHTML="";
        $('buttonsWidth').innerHTML += imageResize.width > 40 ?"<input type='button' value='-' onclick='resizer(\"rw\")' />":"";
        $('buttonsWidth').innerHTML += imageResize.width + stepResizingWidth < widthMain ? " <input type='button' value='+' onclick='resizer(\"ew\")' />" : "";
        
        var ctx = target.getContext('2d');
        
        var img = target.parentNode.getElementsByTagName('img')[0];
        var dx = target.getElementsByTagName("input")[0].value;
        var dy = target.getElementsByTagName("input")[1].value;
        var angle = target.getElementsByTagName("input")[2].value;
           
        updateImageInfo(dx, dy, angle, target.width, target.height);
        ctx.rotate(angle);
        ctx.drawImage(img, dx, dy, target.width, target.height);
            
        //ctx.drawImage(img,0,0,imageResize.width,imageResize.height);
        
    }
    
    function resizeHeight(action)
    {
        
        if(action=='rh')
            imageResize.height -= stepResizingHeight;
        else imageResize.height += stepResizingHeight;
        
        imageResize.width = $('checkboxResize').checked ? imageResize.height * widthHeightRatio : imageResize.width;
        
        $('valueWidth').innerHTML= imageResize.width;
        $('valueHeight').innerHTML= imageResize.height;
        $('buttonsHeight').innerHTML = "";
        $('buttonsHeight').innerHTML += imageResize.height > 40 ? "<input type='button' value='-' onclick='resizer(\"rh\")' />" : "" ;
        $('buttonsHeight').innerHTML += imageResize.height + stepResizingHeight < window.screen.height ? " <input type='button' value='+' onclick='resizer(\"eh\")' />  " : "";
        
        var ctx = target.getContext('2d');
        
        var img = target.parentNode.getElementsByTagName('img')[0];
        var dx = target.getElementsByTagName("input")[0].value;
        var dy = target.getElementsByTagName("input")[1].value;
        var angle = target.getElementsByTagName("input")[2].value;
           
        updateImageInfo(dx, dy, angle, target.width, target.height);
       // ctx.rotate(angle);
        ctx.drawImage(img, dx, dy, target.width, target.height);
    }
    
    function originalSize()
    {
        imageResize.width = originalWidth;
        imageResize.height = originalHeight;
        $('valueWidth').innerHTML= imageResize.width;
        $('valueHeight').innerHTML= imageResize.height;
    }
    
    function closeResize()
    {
        $('divResize').style.display = "none";
    }
    
    function rotateInit()
    {
        $('divRotate').style.display = "block";
    }
    
    function drawExistingImages()
    {
        var arrCanvas = $('main').getElementsByTagName("canvas");
        for(var i=0;i < arrCanvas.length-1;i++) {
            var ctx = arrCanvas[i].getContext("2d");
            var img = arrCanvas[i].getElementsByTagName("img")[0];
            var dx = arrCanvas[i].getElementsByTagName("input")[0].value;
            var dy = arrCanvas[i].getElementsByTagName("input")[1].value;
            var angle = arrCanvas[i].getElementsByTagName("input")[2].value;
            ctx.rotate(angle);
            ctx.drawImage(img, dx, dy, img.width, img.height);
        }
    }
    
    function updateImageInfo(dx, dy, angle, canvasWidth, canvasHeight)
    {
        target.parentNode.getElementsByTagName("input")[0].value=dx;
        target.parentNode.getElementsByTagName("input")[1].value=dy;
        target.parentNode.getElementsByTagName("input")[2].value=angle;
        target.parentNode.getElementsByTagName("input")[3].value=canvasWidth;
        target.parentNode.getElementsByTagName("input")[4].value=canvasHeight;
    }
    
//////////////////////////////
///////////image.js///////////
/////////////////////////////
    function Image(url,name){
        this.url = url;
        this.name = name;
        this.x = 0;
        this.y = 0;
        this.visible = true;
    }


    function setContent(c){
        //'+' of '-'
        //previous en next hidden of niet
        switch (c){
            case '+': ;
                break;
            case '-': index -= 2*numberImages;
                break;
        }
        
        var limit = imageList.length >= index+numberImages ? index+numberImages:imageList.length;
        
        var div = document.getElementById("right");
        div.innerHTML = "";
        while(index < imageList.length && index < limit) {
            div.innerHTML += createEntry(imageList[index]);
            index++;
        }
        
        if(index-numberImages <= 0)
            document.getElementById("previous").style.display = "none";
        else document.getElementById("previous").style.display = "block";
        
        if (index==imageList.length)
            document.getElementById("next").style.display = "none";
        else document.getElementById("next").style.display = "block";
        div.innerHTML += document.getElementById("paging").innerHTML;
    }

    function loadImages(id){
    index = 0;
    rootDir = document.getElementById(id).value;
        try {
		netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
	} catch (e) {
		alert("Permission to save file was denied.");
	}
	var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
    try{
        file.initWithPath(rootDir);
    }
    catch (e){
        alert("There's a possibility you entered a wrong path\nThe path you entered was: " + rootDir);
    }
    // file is the given directory (nsIFile)
    var entries = file.directoryEntries;
    //var list = "";
    
    while(entries.hasMoreElements() ) {
        var entry = entries.getNext();
            entry.QueryInterface(Components.interfaces.nsIFile);
            
                            if(entry.path.toLowerCase().split(".jpeg").length > 1 || entry.path.toLowerCase().split(".jpg").length > 1 || entry.path.toLowerCase().split(".png").length > 1 || entry.path.toLowerCase().split(".gif").length > 1 || entry.path.toLowerCase().split(".bmp").length > 1 || entry.path.toLowerCase().split(".psd").length > 1 || entry.path.toLowerCase().split(".psp").length > 1 || entry.path.toLowerCase().split(".tif").length > 1 ) {
                var img = new Image(entry.path,entry.leafName);
                //list = list+createEntry(img);            
                imageList.push(img);
            }
    }
    setContent('+');
}

    function createEntry(entry){
        return "<span class=\"image\"><img src=\""+entry.url+"\" width=\"150\" onclick=\"Place(\'"+entry.url+"\')\" /></span>";
    }

    function setVisibleHidden(id)
    {
        var el = document.getElementById("id");
        el.className = (el.className=='hidden'?'visible':'hidden');
    }
        
        
////////////////////////////////////////////////////////////////
//////http://luke.breuer.com/tutorial/js_contextmenu.htm///////
//////////////////////////////////////////////////////////////

function InitContext()
{ 
    _divContext.onmouseover = function() { _mouseOverContext = true; };
    _divContext.onmouseout = function() { _mouseOverContext = false; };
   
    $("main").onmousedown = ContextMouseDown;
    $("main").onmouseup = ContextShow;
    
    $('right').style.width = widthRight + "px";
    $('main').style.width = widthMain + "px";
} 

// call from the onMouseDown event, passing the event if standards compliant
function ContextMouseDown(event) {
    if (_mouseOverContext) {
        return;
    }
    // IE is evil and doesn't pass the event object
    if (event == null) event = window.event;
    // we assume we have a standards compliant browser, but check if we have IE
    target = event.target != null ? event.target : event.srcElement;
    // only show the context menu if the right mouse button is pressed
    // and a hyperlink has been clicked (the code can be made more selective)
    if (target.tagName.toLowerCase() == 'canvas')
        _replaceContext = true;
    else if (!_mouseOverContext)
        _divContext.style.display = 'none';
}

function CloseContext()
{
    _mouseOverContext = false;
    _divContext.style.display = 'none';
    $('divResize').style.display = "none";
    $('divRotate').style.display = "none";
}

// call from the onContextMenu event, passing the event
// if this function returns false, the browser's context menu will not show up
function ContextShow(event)
{
    if (_mouseOverContext)
        return;
    // IE is evil and doesn't pass the event object
    if (event == null) event = window.event;
    // we assume we have a standards compliant browser, but check if we have IE
    target = event.target != null ? event.target : event.srcElement;
    
    originalHeight = target.height;
    originalWidth = target.width;
    stepResizingWidth = originalWidth/10;
    stepResizingHeight = originalHeight/10;
    
    if (_replaceContext) {
        //$('delete').onclick = removeImage(target);
        //$('cancel').href = 'http://luke.breuer.com/webmark/?addurl=' + encodeURIComponent(target.title) + '&title=' + encodeURIComponent(target.innerHTML);
        // document.body.scrollTop does not work in IE
        var scrollTop = document.body.scrollTop ? document.body.scrollTop : document.documentElement.scrollTop;
        var scrollLeft = document.body.scrollLeft ? document.body.scrollLeft : document.documentElement.scrollLeft;
        // hide the menu first to avoid an "up-then-over" visual effect
        _divContext.style.display = 'none';
        _divContext.style.left = event.clientX + scrollLeft + 'px';
        _divContext.style.top = event.clientY + scrollTop + 'px';
        _divContext.style.display = 'block';
        _replaceContext = false;
        return false; 
    } 
}

// comes from prototype.js; this is simply easier on the eyes and fingers
function $(id)
{ 
    return document.getElementById(id); 
}

////////////////////////////////////////////////////////
/////http://elouai.com/javascript-drag-and-drop.php////
//////////////////////////////////////////////////////

function movemouse(e)
{
  if (isdrag)
  {
    dobj.style.left = nn6 ? tx + e.clientX - x : tx + event.clientX - x;
    dobj.style.top  = nn6 ? ty + e.clientY - y : ty + event.clientY - y;
    return false;
  }
}

function selectmouse(e) 
{
  var fobj       = nn6 ? e.target : event.srcElement;
  var topelement = nn6 ? "HTML" : "BODY";

  while (fobj.tagName != topelement && fobj.className != "dragme")
  {
    fobj = nn6 ? fobj.parentNode : fobj.parentElement;
  }

  if (fobj.className=="dragme")
  {
    isdrag = true;
    dobj = fobj;
    tx = parseInt(dobj.style.left+0);
    ty = parseInt(dobj.style.top+0);
    x = nn6 ? e.clientX : event.clientX;
    y = nn6 ? e.clientY : event.clientY;
    document.onmousemove=movemouse;
    return false;
  }
}

document.onmousedown=selectmouse;
document.onmouseup=new Function("isdrag=false");

/////////////////////////////////////////////////////////////////////////////////////
//////http://javascript.internet.com/image-effects/image-rotate-with-canvas.html////
///////////////////////////////////////////////////////////////////////////////////

		/* This script and many more are available free online at
The JavaScript Source!! http://javascript.internet.com
Created by: Benoit Asselin | http://www.ab-d.fr */

function rotate(p_deg) {
	if(target.parentNode.getElementsByTagName("canvas")[0]) {
		/*
		Ok!: Firefox 2, Safari 3, Opera 9.5b2
		No: Opera 9.27
		*/
               var image = target.parentNode.getElementsByTagName("img")[0];
		var canvas = target.parentNode.getElementsByTagName("canvas")[0];
		var canvasContext = canvas.getContext('2d');
		
		switch(p_deg) {
			default :
			case 0 :
				canvas.setAttribute('width', canvas.width);
				canvas.setAttribute('height', canvas.height);
				canvasContext.rotate(p_deg * Math.PI / 180);
				canvasContext.drawImage(image, 0, 0, canvas.width, canvas.height);
                                updateImageInfo(0,0,p_deg * Math.PI / 180, canvas.width, canvas.height);
				break;
			case 90 :
				canvas.setAttribute('width', canvas.height);
				canvas.setAttribute('height', canvas.width);
				canvasContext.rotate(p_deg * Math.PI / 180);
				canvasContext.drawImage(image, 0, -canvas.height, canvas.width, canvas.height);
				updateImageInfo(0,-canvas.height,p_deg * Math.PI / 180, canvas.width, canvas.height);
                                break;
			case 180 :
				canvas.setAttribute('width', canvas.width);
				canvas.setAttribute('height', canvas.height);
				canvasContext.rotate(p_deg * Math.PI / 180);
				canvasContext.drawImage(image, -canvas.width, -canvas.height, canvas.width, canvas.height);
				updateImageInfo(-canvas.width,-canvas.height,p_deg * Math.PI / 180, canvas.width, canvas.height);
                                break;
			case 270 :
			case -90 :
				canvas.setAttribute('width', canvas.height);
				canvas.setAttribute('height', canvas.width);
				canvasContext.rotate(p_deg * Math.PI / 180);
				canvasContext.drawImage(image, -canvas.width, 0, canvas.width, canvas.height);
				updateImageInfo(-canvas.width,0,p_deg * Math.PI / 180, canvas.width, canvas.height);
                                break;
		};
		
	} else {
		/*
		Ok!: MSIE 6 et 7
		*/
		var image = target.parentNode.getElementsByTagName("img")[0];
		switch(p_deg) {
			default :
			case 0 :
				image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=0)';
				break;
			case 90 :
				image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=1)';
				break;
			case 180 :
				image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=2)';
				break;
			case 270 :
			case -90 :
				image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=3)';
				break;
		};
		
	};
};

// Multiple onload function created by: Simon Willison
// http://simonwillison.net/2004/May/26/addLoadEvent/
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

/*
addLoadEvent(function() {
	var image = document.getElementById('image');
	var canvas = document.getElementById('canvas');
	if(canvas.getContext) {
		image.style.visibility = 'hidden';
		image.style.position = 'absolute';
	} else {
		canvas.parentNode.removeChild(canvas);
	};
	
	rotate(0);
});*/

</script>
  </body>
</html>
